<?php

namespace App\Library\Logic;

use App\Models\AuctionBailModel;
use Exception;
use Illuminate\Database\Eloquent\Model;

class AuctionBailLogic extends AuctionBailModel
{
    /**
     * paySuccess
     * @param int $id
     * @param string $payAt
     * @return int
     */
    public static function paySuccess(int $id, string $payAt): int
    {
        return self::query()->where(humpToLine(['id' => $id, 'status' => 1, 'statusPay' => 0, 'payAt' => null]))
            ->update(humpToLine([
                'status' => 2, 'payAt' => $payAt, 'statusPay' => 1
            ]));
    }

    /**
     * add
     * @param Model $auction
     * @return Model|null
     */
    public static function add(Model $auction): ?Model
    {
        return self::insertForModel([
            'userId' => USERID,
            'auctionId' => $auction->id,
            'title' => '保证金:' . $auction->bail_price * 1,
            'payPrice' => $auction->bail_price,
            'orderPrice' => $auction->bail_price,
        ]);
    }

    /**
     * myBailOfAuctionId
     * @param int $auctionId
     * @return Model|null
     */
    public static function myBailOfAuctionId(int $auctionId): ?Model
    {
        return self::query()->where(['auction_id' => $auctionId, 'user_id' => USERID])->first();
    }

    /**
     * auctionBailRefund
     * @throws Exception
     */
    public static function auctionBailRefund(object $auction, int $userId = 0): void
    {
        cache()->forget('bid:' . $auction->serial_number);
        cache()->forget('bidHigher:' . $auction->serial_number);
        $query = AuctionBailLogic::query()->where(humpToLine([
            'auctionId' => $auction->id,
            'status' => 2,
            'statusPay' => 1,
            'statusBail' => 0,
        ]))->whereNotNull('pay_at')->whereNull('refund_at');
        if ($userId > 0) $query->where('user_id', '<>', $userId);
        $array = $query->pluck('serial_number')->toArray();
        foreach ($array as $v) mq('auctionBailRefund', $v);
    }
}
